<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" inline label-width="68px">
      <el-form-item label="姓名" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="手机号" prop="telephone">
        <el-input v-model="queryParams.telephone" placeholder="请输入手机号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="注册时间" prop="createTime">
        <el-date-picker 
          v-model="queryParams.createTime" 
          type="date" 
          value-format="yyyy-MM-dd" 
          placeholder="选择注册时间"
          clearable 
        />
      </el-form-item>
      <el-form-item label="是否拉黑" prop="isBlacklisted">
        <el-select v-model="queryParams.isBlacklisted" placeholder="请选择" clearable style="width: 100%">
          <el-option label="正常" value="0" />
          <el-option label="已拉黑" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="2">
        <el-button
          type="warning"
          plain
          icon="el-icon-circle-close"
          size="mini"
          :disabled="!ids.length"
          @click="handleBatchBlacklist"
          v-hasPermi="['system:user:blacklist']"
        >
          {{ batchBlacklistText }}
        </el-button>
      </el-col>
      <el-col :span="2">
        <el-button
          type="info"
          plain
          icon="el-icon-key"
          size="mini"
          :disabled="!ids.length"
          @click="handleBatchResetPwd"
          v-hasPermi="['system:user:resetPwd']"
        >
          批量重置密码
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="userList" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="60" align="center" />
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="手机号" align="center" prop="telephone" />
      <el-table-column label="头像" align="center" width="100">
        <template slot-scope="scope">
          <el-avatar size="medium">
            <img v-if="scope.row.avatar" :src="scope.row.avatar" alt="用户头像" @error="() => scope.row.avatar = defaultAvatar"/>
            <span v-else>{{ (scope.row.name || '未知').charAt(0) }}</span>
          </el-avatar>
        </template>
      </el-table-column>
      <el-table-column label="余额" align="center" prop="balance" />
      <el-table-column label="是否拉黑" align="center" prop="isBlacklisted">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isBlacklisted === 1 ? 'danger' : 'success'">
            {{ scope.row.isBlacklisted === 1 ? '已拉黑' : '正常' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="注册时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">{{ parseTime(scope.row.createTime) }}</template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button 
            size="mini" 
            type="text" 
            :icon="scope.row.isBlacklisted === 1 ? 'el-icon-check' : 'el-icon-circle-close'"
            :style="{color: scope.row.isBlacklisted === 1 ? 'green' : 'red'}"
            @click="handleBlacklist(scope.row)" 
            v-hasPermi="['system:user:blacklist']"
          >
            {{ scope.row.isBlacklisted === 1 ? '解除拉黑' : '拉黑' }}
          </el-button>
          <el-button 
            size="mini" 
            type="text" 
            icon="el-icon-key"
            @click="handleResetPwd(scope.row)"
            v-hasPermi="['system:user:resetPwd']"
          >
            重置密码
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination 
      v-show="total > 0" 
      :total="total" 
      :page.sync="queryParams.pageNum" 
      :limit.sync="queryParams.pageSize"
      @pagination="getList" 
    />

    <!-- 拉黑原因弹窗 -->
    <el-dialog 
      title="拉黑用户" 
      :visible.sync="blacklistDialogVisible" 
      width="500px"
      :before-close="handleDialogClose"
    >
      <el-form ref="blacklistForm" :model="blacklistForm" label-width="80px">
        <el-form-item 
          label="拉黑原因" 
          prop="reason"
          :rules="[
            { required: true, message: '请输入拉黑原因', trigger: 'blur' },
            { min: 2, max: 200, message: '原因长度在 2 到 200 个字符', trigger: 'blur' }
          ]"
        >
          <el-input v-model="blacklistForm.reason" type="textarea" rows="4" placeholder="请输入拉黑原因"></el-input>
        </el-form-item>
        <el-form-item 
          label="处罚内容" 
          prop="content"
          :rules="[
            { required: true, message: '请输入处罚内容', trigger: 'blur' },
            { min: 2, max: 200, message: '内容长度在 2 到 200 个字符', trigger: 'blur' }
          ]"
        >
          <el-input v-model="blacklistForm.content" type="textarea" rows="3" placeholder="请输入处罚内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="blacklistDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmBlacklist">确定</el-button>
      </div>
    </el-dialog>

    <!-- 重置密码确认弹窗 -->
    <el-dialog 
      :title="resetPwdTitle" 
      :visible.sync="resetPwdDialogVisible" 
      width="400px"
    >
      <div v-if="!resetPwdResult">
        <p>确定要重置选中的{{ resetIds.length }}个用户的密码吗？</p>
        <p style="color: #f56c6c; margin-top: 10px;">重置后密码将恢复为默认密码，用户需要重新设置。</p>
      </div>
      <div v-else>
        <p style="color: #67c23a; font-weight: bold;">密码重置成功！</p>
        <p>新密码为：<span style="color: #409EFF; font-weight: bold;">{{ defaultPassword }}</span></p>
        <p style="color: #f56c6c; margin-top: 10px;">请告知用户使用新密码登录，并尽快修改密码。</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="!resetPwdResult" @click="resetPwdDialogVisible = false">取消</el-button>
        <el-button 
          v-if="!resetPwdResult" 
          type="primary" 
          @click="confirmResetPwd"
          :loading="resetPwdLoading"
        >确定</el-button>
        <el-button 
          v-else 
          type="primary" 
          @click="resetPwdDialogVisible = false"
        >关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { 
  listUser, 
  updateBlacklistStatus, 
  addToBlacklist, 
  resetUserPwd, 
  batchResetUserPwd 
} from "@/api/user/customer"
// 引入批量解除拉黑API
import { batchRemoveFromBlacklist } from "@/api/user/customer"
import Pagination from "@/components/Pagination"
import RightToolbar from "@/components/RightToolbar"

export default {
  components: { Pagination, RightToolbar },
  data() {
    return {
      loading: false,
      ids: [],
      resetIds: [],
      showSearch: true,
      total: 0,
      userList: [],
      defaultAvatar: 'https://picsum.photos/200/200?random=1',
      defaultPassword: '123456', // 默认密码
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        telephone: null,
        createTime: null,
        isBlacklisted: null
      },
      blacklistDialogVisible: false,
      blacklistForm: {
        customerId: null,
        name: null,
        reason: '',
        content: ''
      },
      batchOperate: {
        ids: [],
        targetStatus: 0
      },
      // 重置密码相关
      resetPwdDialogVisible: false,
      resetPwdLoading: false,
      resetPwdResult: false,
      resetPwdTitle: '重置密码确认'
    }
  },
  computed: {
    batchBlacklistText() {
      if (!this.ids.length) return "批量拉黑"
      const allBlacklisted = this.userList
        .filter(item => this.ids.includes(item.id))
        .every(item => item.isBlacklisted === 1)
      return allBlacklisted ? "批量解除拉黑" : "批量拉黑"
    }
  },
  created() {
    this.getList()
  },
  methods: {
    parseTime(time) {
      if (!time) return ""
      try {
        const date = new Date(time)
        return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
      } catch {
        return ""
      }
    },

    getList() {
      this.loading = true
      listUser(this.queryParams)
        .then(res => {
          if (res?.code === 200) {
            this.userList = res.rows || []
            this.total = res.total || 0
          } else {
            this.$message.error(res?.msg || "获取数据失败")
            this.userList = []
            this.total = 0
          }
        })
        .catch(() => {
          this.$message.error("网络错误，获取数据失败")
          this.userList = []
          this.total = 0
        })
        .finally(() => this.loading = false)
    },

    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    resetQuery() {
      this.$refs.queryForm?.resetFields()
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        name: null,
        telephone: null,
        createTime: null,
        isBlacklisted: null
      }
      this.getList()
    },

    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
    },

    handleBlacklist(row) {
      const targetStatus = row.isBlacklisted === 1 ? 0 : 1
      const actionText = targetStatus === 1 ? "拉黑" : "解除拉黑"
      
      if (targetStatus === 0) {
        this.confirmStatusChange(row.id, targetStatus, actionText)
        return
      }

      this.blacklistForm = {
        customerId: row.id,
        name: row.name,
        reason: '',
        content: ''
      }
      this.blacklistDialogVisible = true
    },

    handleBatchBlacklist() {
      if (!this.ids.length) return this.$modal.msgWarning("请选择需要操作的用户")
      
      const firstItem = this.userList.find(item => this.ids.includes(item.id))
      const targetStatus = firstItem.isBlacklisted === 1 ? 0 : 1
      const actionText = targetStatus === 1 ? "拉黑" : "解除拉黑"
      
      if (targetStatus === 0) {
        // 解除拉黑操作
        if (this.ids.length === 1) {
          this.confirmStatusChange(firstItem.id, targetStatus, actionText)
        } else {
          this.confirmBatchRemoveBlacklist()
        }
        return
      }

      // 拉黑操作保持不变
      this.batchOperate = { ids: this.ids, targetStatus }
      this.blacklistForm = {
        customerId: firstItem.id,
        name: firstItem.name,
        reason: '',
        content: ''
      }
      this.blacklistDialogVisible = true
    },

    // 单个用户重置密码
    handleResetPwd(row) {
      this.resetIds = [row.id]
      this.resetPwdTitle = `重置用户【${row.name}】的密码`
      this.resetPwdDialogVisible = true
      this.resetPwdResult = false
    },

    // 批量重置密码
    handleBatchResetPwd() {
      if (!this.ids.length) return this.$modal.msgWarning("请选择需要重置密码的用户")
      
      this.resetIds = this.ids
      this.resetPwdTitle = `批量重置密码（${this.ids.length}个用户）`
      this.resetPwdDialogVisible = true
      this.resetPwdResult = false
    },

    // 确认重置密码
    confirmResetPwd() {
      this.resetPwdLoading = true
      
      const apiCall = this.resetIds.length === 1 
        ? resetUserPwd({ id: this.resetIds[0] })
        : batchResetUserPwd({ ids: this.resetIds })
      
      apiCall
        .then(res => {
          if (res.code === 200) {
            this.resetPwdResult = true
            // 如果后端返回了新密码，使用返回的密码，否则使用默认密码
            if (res.data && res.data.password) {
              this.defaultPassword = res.data.password
            }
            this.$message.success("密码重置成功")
          } else {
            this.$message.error(res.msg || "密码重置失败")
            this.resetPwdDialogVisible = false
          }
        })
        .catch(() => {
          this.$message.error("网络错误，密码重置失败")
          this.resetPwdDialogVisible = false
        })
        .finally(() => {
          this.resetPwdLoading = false
        })
    },

    confirmBlacklist() {
      this.$refs.blacklistForm.validate(valid => {
        if (valid) {
          const params = this.batchOperate.ids.length 
            ? { ...this.blacklistForm, customerIds: this.batchOperate.ids }
            : this.blacklistForm

          addToBlacklist(params)
            .then(res => {
              if (res.code === 200) {
                this.$message.success(this.batchOperate.ids.length ? "批量拉黑成功" : "拉黑成功")
                this.blacklistDialogVisible = false
                this.batchOperate.ids = []
                this.getList()
              } else {
                this.$message.error(res.msg || "操作失败")
              }
            })
        }
      })
    },

    confirmStatusChange(userId, status, actionText) {
      this.$modal.confirm(`确定要${actionText}该用户吗？`).then(() => {
        return updateBlacklistStatus({ id: userId, isBlacklisted: status })
      }).then(res => {
        if (res.code === 200) {
          this.$modal.msgSuccess(`${actionText}成功`)
          this.getList()
        } else {
          this.$modal.msgError(res.msg || "操作失败")
        }
      }).catch(() => {})
    },

    // 新增批量解除拉黑确认方法
    confirmBatchRemoveBlacklist() {
      this.$modal.confirm(`确定要解除选中的${this.ids.length}个用户的拉黑状态吗？`).then(() => {
        return batchRemoveFromBlacklist(this.ids)
      }).then(res => {
        if (res.code === 200) {
          this.$modal.msgSuccess(`批量解除拉黑成功`)
          this.getList()
        } else {
          this.$modal.msgError(res.msg || "操作失败")
        }
      }).catch(() => {})
    },

    handleDialogClose() {
      this.$refs.blacklistForm.resetFields()
      this.blacklistDialogVisible = false
      this.batchOperate.ids = []
    }
  }
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>